/**
 * New node file
 */
var http = require('http');
var util = require('util');
var url  = require('url');
http.createServer(function(req, res){
    
    var headers = req.headers;
    var host = headers['host'].indexOf(':') >0 ? headers['host'].split(":")[0] : headers['host'];
    var port = headers['host'].indexOf(':') >0 ? headers['host'].split(":")[1] : '80';
    if(headers['proxycircle'] == '1') {
    	res.end('proxy circle')
    }
    console.log(new Date().toGMTString() + ' ip: ' + req.ips + ' ' + util.inspect(headers));
    
    var requestcache = null;
    var option = {
    	host : host,
    	port : parseInt(port),
    	method : req.method,
    	path : req.url.indexOf('static=false') < 0 ? req.url + '&static=false' : req.url,
    	headers : headers
    }
    
    option.headers['proxycircle'] = '1'
    
    req.on('data', function(chunk){
    	if(requestcache == null){
    		requestcache = chunk;
    	}else{
    		requestcache = Buffer.concat(requestcache, chunk);
    	}
    });
    
    req.on('error', function(){
    	console.log('error');
    })
    
    req.on('end', function(){
    	var proxyRequest = http.request(option, function(proxyResponse){
  		
	  		res.writeHead(proxyResponse.statusCode, proxyResponse.headers);
	  		proxyResponse.on('data', function(data){
	    		res.write(data);
	    	});
	    	proxyResponse.on('end', function(){
	    		res.end();
	    	})
	    }).on('error', function(e){
	    		console.log('error proxy '+  e.message);
	    		res.end();
	    });
	    if(requestcache != null){
	    	proxyRequest.write(requestcache);
	    }
	    proxyRequest.end();
    })
}).listen(8080);